import { PaginatedData, PaginationResponse } from '@/types'
import { Recommendation, Likes } from '@/types/recommend'
import { ROUTE_APP } from '@/lib/consts'

const category = 'sun'
export async function loadFriendSite(
  params: Partial<Recommendation>
): Promise<PaginatedData<Recommendation>> {
  try {
    //默认参数 sun
    params.category = params.category || category
    const response = await fetch(
      `${ROUTE_APP}/recommend?query=${encodeURIComponent(
        JSON.stringify(params)
      )}`
    )
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const data: PaginationResponse<Recommendation> = await response.json()
    return data.data
  } catch (error) {
    console.error('Error loading friend sites:', error)
    throw error
  }
}

// 创建推荐
export async function createRecommendation(
  recommendation: Partial<Recommendation>
): Promise<Recommendation> {
  try {
    const response = await fetch(`${ROUTE_APP}/recommend`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(recommendation)
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const data = await response.json()
    return data
  } catch (error) {
    console.error('Error creating recommendation:', error)
    throw error
  }
}

// 更新推荐
export async function updateRecommendation(
  id: string,
  recommendation: Partial<Recommendation>
): Promise<Recommendation> {
  try {
    const response = await fetch(`${ROUTE_APP}/recommend/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(recommendation)
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const data = await response.json()
    return data
  } catch (error) {
    console.error('Error updating recommendation:', error)
    throw error
  }
}

// 删除推荐
export async function deleteRecommendation(id: string): Promise<void> {
  try {
    const response = await fetch(`${ROUTE_APP}/recommend/${id}`, {
      method: 'DELETE'
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
  } catch (error) {
    console.error('Error deleting recommendation:', error)
    throw error
  }
}

// 获取单个推荐详情
export async function getRecommendation(id: string): Promise<Recommendation> {
  try {
    const response = await fetch(`${ROUTE_APP}/recommend/${id}`)

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const data = await response.json()
    return data
  } catch (error) {
    console.error('Error getting recommendation:', error)
    throw error
  }
}

// 点赞推荐
export async function likeRecommendation(entityId: string): Promise<Likes> {
  try {
    const likeData: Partial<Likes> = {
      entity_id: entityId,
      entity_type: 3, // 推荐类型
      status: 1
    }

    const response = await fetch(`${ROUTE_APP}/likes`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(likeData)
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const data = await response.json()
    return data
  } catch (error) {
    console.error('Error liking recommendation:', error)
    throw error
  }
}

// 取消点赞
export async function unlikeRecommendation(likeId: string): Promise<void> {
  try {
    const response = await fetch(`${ROUTE_APP}/likes/${likeId}`, {
      method: 'DELETE'
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
  } catch (error) {
    console.error('Error unliking recommendation:', error)
    throw error
  }
}

// 获取点赞信息
export async function getLikeByEntityId(
  entity_type: number,
  entity_id: string,
  type?: number
): Promise<PaginatedData<Likes> | null> {
  try {
    let url = `${ROUTE_APP}/likes?entity_type=${entity_type}&entity_id=${entity_id}&page=1&size=1`
    if (type !== undefined) {
      url += `&type=${type}`
    }

    const response = await fetch(url)

    if (!response.ok) {
      if (response.status === 404) {
        return null
      }
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const data: PaginationResponse<Likes> = await response.json()
    return data.data
  } catch (error) {
    console.error('Error getting like by entity id:', error)
    throw error
  }
}

// 获取自己的点赞数据 只会有一条，但是是返回分页的格式【通用的方法】
export async function getLikeByEntityIdAndSelf(
  entity_type: number,
  entity_id: string
): Promise<PaginatedData<Likes> | null> {
  try {
    const params = {
      parms: JSON.stringify({
        // 只查自己的数据
        flag_filter: 3
      }),
      entity_type,
      entity_id,
      page: 1,
      size: 5
    }

    const queryString = new URLSearchParams(
      Object.entries(params).reduce(
        (acc, [key, value]) => {
          acc[key] = typeof value === 'string' ? value : String(value)
          return acc
        },
        {} as Record<string, string>
      )
    ).toString()
    const url = `${ROUTE_APP}/likes?${queryString}`

    const response = await fetch(url)

    if (!response.ok) {
      if (response.status === 404) {
        return null
      }
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const data: PaginationResponse<Likes> = await response.json()
    return data.data
  } catch (error) {
    console.error('Error getting like by entity id and self:', error)
    throw error
  }
}

// 添加点赞
export async function addLike(
  entity_type: number,
  entity_id: string,
  type: number = 1
): Promise<Likes> {
  try {
    const likeData = {
      entity_type,
      entity_id,
      type
    }

    const response = await fetch(`${ROUTE_APP}/likes`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(likeData)
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const data = await response.json()
    return data
  } catch (error) {
    console.error('Error adding like:', error)
    throw error
  }
}

// 取消点赞
export async function removeLike(id: string): Promise<void> {
  try {
    const response = await fetch(`${ROUTE_APP}/likes/${id}`, {
      method: 'DELETE'
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
  } catch (error) {
    console.error('Error removing like:', error)
    throw error
  }
}

// 更新，点赞改成踩
export async function updateLike(
  id: string,
  entity_type: number,
  entity_id: string,
  type: number = 2
): Promise<Likes> {
  try {
    const likeData = {
      entity_type,
      entity_id,
      type
    }

    const response = await fetch(`${ROUTE_APP}/likes/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(likeData)
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const data = await response.json()
    return data
  } catch (error) {
    console.error('Error updating like:', error)
    throw error
  }
}
